package cn.iocoder.yudao.module.promotion.fod.service;

import cn.iocoder.yudao.framework.business.basic.service.impl.AbstractService;
import cn.iocoder.yudao.module.api.promotion.fod.enums.FirstOrderDiscountTypeEnum;
import cn.iocoder.yudao.module.promotion.fod.dao.FirstOrderDiscountRecordMapper;
import cn.iocoder.yudao.module.promotion.fod.pojo.po.FirstOrderDiscountBase;
import cn.iocoder.yudao.module.promotion.fod.pojo.po.FirstOrderDiscountRecord;
import cn.iocoder.yudao.module.promotion.fod.pojo.vo.FirstOrderDiscountBaseVO;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;

/**
 * 平台首单优惠活动 Service 实现类
 *
 * @author 山野羡民
 */
abstract class FirstOrderDiscountInternalBaseService<DO extends FirstOrderDiscountBase, VO extends FirstOrderDiscountBaseVO> extends AbstractService<DO, VO> implements FirstOrderDiscountInternalService<DO> {
    @Resource
    private FirstOrderDiscountRecordMapper firstOrderDiscountRecordMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void applyDiscount(FirstOrderDiscountTypeEnum type, Long userId, String tradeNo, Integer originalPrice, Integer discountPrice) {
        // 记录优惠详情
        FirstOrderDiscountRecord recordDO = new FirstOrderDiscountRecord();
        recordDO.setUserId(userId);
        recordDO.setType(type.getValue());
        recordDO.setTradeNo(tradeNo);
        recordDO.setPrice(originalPrice);
        recordDO.setDiscountPrice(discountPrice);
        firstOrderDiscountRecordMapper.insert(recordDO);
        // 更新活动状态为已使用
        DO activityDO = getOrCreate(userId);
        activityDO.setUsed(true);
        getInjectedMapper().updateById(activityDO);
    }

}